<?php

/**
* <class description>
* 
* @author
* @link
*/

class Users extends Controller
{
    public function __construct()
    {
        parent::Controller();      
        $this->load->helper('form'); 
        $this->load->library("form_validation");    
        $this->load->model("usermodel");        

    }    

    /**
    * Show login form
    * 
    * @access
    * @param
    * @return
    */
    public function login()
    {

        //if(session_check() === TRUE){ 
        //    return;
        //}
        
        $error = FALSE;
        if($this->input->post("login_submit") !== FALSE){
          
            if(validate_token("login",$this->input->post("login_token",TRUE))){

                if($this->_validate_login_form()){

                    // no errors, check if user is valid
                    $valid_user = $this->usermodel->check_valid_user($this->input->post('login_username',TRUE),$this->input->post('login_password',TRUE));

                    if ($valid_user !== FALSE)
                    {
                         
                        // register user session
                        session_create($valid_user);

                        //store last login in user table and increase number of logins
                        $this->usermodel->register_user_login($valid_user['id']);

                        //redirect user
                        $this->_redirect_after_login();
                          
                        
                    } else {
                        
                        // Wrong credentials!
                        $error = '<p class="error">'.$this->lang->line('LoginWrongCredentials').'</p>';  

                    }  

                }
            }
        }

        $token = generate_token("login",10);
        $this->load->view("users_login_form",array("token" => $token, 'error' => $error));                    
        
    }

    public function vip_login()
    {

        //if(session_check() === TRUE){ 
        //    return;
        //}

        
        $error = FALSE;
        if($this->input->post("viplogin_submit") !== FALSE){
          
            if(validate_token("vip",$this->input->post("vip_token",TRUE))){

                if($this->_validate_viplogin_form()){

                    // no errors, check if user is valid
                    if ($this->input->post('vip_code') == VIP_CODE) {
                         
                        // register user session
                        $valid_user["id"] = 'vip';
                        $valid_user["username"] = 'vip';
                        session_create($valid_user);

                        //redirect user
                        $this->_redirect_after_login();

                        
                    } else {
                        
                        // Wrong credentials!
                        $error = '<p class="error">'.$this->lang->line('LoginWrongVipCode').'</p>';  

                    }  

                }
            }
        }

        $token = generate_token("vip",10);
        $this->load->view("users_viplogin_form",array("token" => $token, 'error' => $error));                    
        
    }

    private function _validate_login_form(){  
        $config = array(
                        array(
                         'field'   => 'login_username',
                         'label'   => 'Username',
                         'rules'   => 'trim|xss_clean|required|valid_email'
                        ),
                        array(
                         'field'   => 'login_password',
                         'label'   => 'Password',
                         'rules'   => 'required|xss_clean|min_length[4]|max_length[20]'
                        )
                        
                    );

        $this->form_validation->set_rules($config);       
        $this->form_validation->set_error_delimiters('<p class="error">', '</p>'); 
        
        if ($this->form_validation->run($this) == FALSE){
            return FALSE;
        }else
            return TRUE;

    }
    private function _validate_viplogin_form(){  
        $config = array(
                        array(
                         'field'   => 'vip_code',
                         'label'   => 'VIP Code',
                         'rules'   => 'required|xss_clean'
                        )
                        
                    );

        $this->form_validation->set_rules($config);       
        $this->form_validation->set_error_delimiters('<p class="error">', '</p>'); 
        
        if ($this->form_validation->run($this) == FALSE){
            return FALSE;
        }else
            return TRUE;

    }

    private function _redirect_after_login() 
    {
        redirect(get_referrer()); 
    }

    public function logout()
    {
        session_delete();
        redirect('');
    }
    

    /**
    * Show register form
    * 
    * @access
    * @param
    * @return
    */
    public function register()
    { 

        /*
        if(session_check() === TRUE){ 
            return;
        }
        */

        $error = "";

        if($this->input->post("register_submit") !== FALSE){

            if(validate_token("register",$this->input->post("register_token",TRUE))){
                 
                if($this->_validate_register_form()){

                    if($error == ""){

                    $new_id =  uniqid('',TRUE);


                        $data['user_data'] = array(
                                "id_Users" => $new_id,
                                "UserName_users" => $this->input->post("email",TRUE),
                                "UserPassword_users" => sha1($this->input->post("password",TRUE))
                                ); 
                        $data['user_details'] = array(
                                "id_Users" => $new_id,
                                "Title_UsersDetails" => $this->input->post("title",TRUE),         
                                "FirstName_UsersDetails" => $this->input->post("forename",TRUE),         
                                "LastName_UsersDetails" => $this->input->post("surname",TRUE),         
                                "CompanyName_UsersDetails" => $this->input->post("companyname",TRUE),         
                                "Address_UsersDetails" => $this->input->post("clientaddress",TRUE),         
                                "City_UsersDetails" => $this->input->post("city",TRUE),         
                                "State_UsersDetails" => $this->input->post("state_province_county",TRUE),         
                                "ZipCode_UsersDetails" => $this->input->post("zip",TRUE),         
                                "Country_UsersDetails" => $this->input->post("country",TRUE),         
                                "DaytimePhone_UsersDetails" => $this->input->post("phonenumber",TRUE),         
                                "Mobile_UsersDetails" => $this->input->post("mobile",TRUE),         
                                "Email_UsersDetails" => $this->input->post("email",TRUE),         
                                "ProfessionalDesignations" => $this->input->post("professionaldesignation",TRUE),         
                                "DateJoined_UsersDetails" => date("Y-m-d H:i:s"),
                                "LastLogin_UsersDetails" => date("Y-m-d H:i:s"),
                                "NumberLogins_UsersDetails" => 1
                                ); 


                        if($this->usermodel->create_new_user($data['user_data']) !== FALSE){

                            // store user details
                            $this->usermodel->insert_user_details($data['user_details']);    

                            // email registration confirmation
                            $this->_send_registration_confirmation_email();

                            // email admin if user has questions/comments
                            if ($this->input->post("comments") !== "")
                                $this->_send_registration_comments_email();

                            // log in user
                            session_create(array('id' => $new_id, 'username' => $this->input->post("email",TRUE)));

                            //redirect user
                            $this->_redirect_after_login();

                           //$this->load->view("users_register_success");  
                           
                           return;   
                        }
                    }
                }
            }
        }

        $token = generate_token("register",20);
        $this->load->view("users_register_form", array("token" => $token, "error" => $error));
        
    }


    private function _validate_register_form(){
        
        $config = array(
                        array(
                         'field'   => 'title',
                         'label'   => 'Title',
                         'rules'   => 'trim|required|xss_clean|max_length[8]'
                        ),
                        array(
                         'field'   => 'forename',
                         'label'   => 'Forename',
                         'rules'   => 'trim|required|xss_clean|max_length[100]'
                        ),
                        array(
                         'field'   => 'surname',
                         'label'   => 'Surname',
                         'rules'   => 'trim|required|xss_clean|max_length[100]'
                        ),
                        array(
                         'field'   => 'companyname',
                         'label'   => 'Company Name',
                         'rules'   => 'trim|required|xss_clean|max_length[200]'
                        ),
                        array(
                         'field'   => 'clientaddress',
                         'label'   => 'Address',
                         'rules'   => 'trim|required|xss_clean|max_length[250]'
                        ),
                        array(
                         'field'   => 'city',
                         'label'   => 'City',
                         'rules'   => 'trim|xss_clean|required|max_length[100]'
                        ),
                        array(
                         'field'   => 'state_province_county',
                         'label'   => 'State/Province/County',
                         'rules'   => 'trim|xss_clean|required|max_length[100]'
                        ),
                        array(
                         'field'   => 'zip',
                         'label'   => 'ZIP/Postal Code',
                         'rules'   => 'trim|xss_clean|required|max_length[50]'
                        ),
                        array(
                         'field'   => 'country',
                         'label'   => 'Country',
                         'rules'   => 'trim|xss_clean|required'
                        ),
                        array(
                         'field'   => 'phonenumber',
                         'label'   => 'Phone Number',
                         'rules'   => 'trim|xss_clean|required|max_length[30]'
                        ),
                        array(
                         'field'   => 'mobile',
                         'label'   => 'Mobile Phone',
                         'rules'   => 'trim|xss_clean|required|max_length[30]'
                        ), 
                        array(
                         'field'   => 'email',
                         'label'   => 'Email Address',
                         'rules'   => 'trim|xss_clean|required|valid_email|callback_check_duplicated_email'
                        ),
                        array(
                         'field'   => 'email2',
                         'label'   => 'Email Address (verification)',
                         'rules'   => 'trim|xss_clean|required|matches[email]'
                        ),
                        array(
                         'field'   => 'password',
                         'label'   => 'Password',
                         'rules'   => 'required|min_length[4]|max_length[20]'
                        ),
                        array(
                         'field'   => 'password2',
                         'label'   => 'Password (verification)',
                         'rules'   => 'required|matches[password]'
                        ),
                        array(
                         'field'   => 'professionaldesignation',
                         'label'   => 'Professional Designation',
                         'rules'   => 'required'
                        ),
                        array(
                         'field'   => 'brochure',
                         'label'   => '',
                         'rules'   => ''
                        ),
                        array(
                         'field'   => 'mailinglist',
                         'label'   => '',
                         'rules'   => ''
                        ),
                        array(
                         'field'   => 'comments',
                         'label'   => '',
                         'rules'   => 'trim|xss_clean'
                        )        
                    );
        
                                                 
        $this->form_validation->set_rules($config);       
        $this->form_validation->set_error_delimiters('<p class="error">', '</p>');
        
        if ($this->form_validation->run($this) == FALSE){
            return FALSE;
        }else
            return TRUE;

    }

    public function check_duplicated_email($email){ 

        if($this->usermodel->is_duplicated('Username_Users', $email)){

            $this->form_validation->set_message('check_duplicated_email', $this->lang->line('EmailAlreadyExists'));
            return FALSE;

        }else{

            return TRUE;    

        }
        
    }   

    private function _send_registration_confirmation_email(){

        $this->load->helper('send_email');     

        $template_file = EMAIL_TEMPLATES_FOLDER.'registration_confirmation'.INSTANCE_FILE_SUFFIX.'.html';
        $template_data = array(           
                "FORENAME" => $this->input->post("forename",TRUE),
                "SURNAME" => $this->input->post("surname",TRUE),
                "EMAIL" => $this->input->post("email",TRUE),
                "PASSWORD" => $this->input->post("password",TRUE)
                );

        $sender_name = $this->input->post("forename",TRUE).' '.$this->input->post("surname",TRUE);

        send_email(EMAIL_SENDER, 
                    EMAIL_SENDER_NAME, 
                    $this->input->post("email",TRUE), 
                    $this->lang->line('Regsitration_confirmation_subject'), 
                    $template_file,
                    $template_data);       

    }      

    private function _send_registration_comments_email(){

        $this->load->helper('send_email');     

        $template_file = EMAIL_TEMPLATES_FOLDER.'registration_comments'.INSTANCE_FILE_SUFFIX.'.html';
        $template_data = array(           
                "FORENAME" => $this->input->post("forename",TRUE),
                "TITLE" => $this->input->post("forename",TRUE),
                "SURNAME" => $this->input->post("surname",TRUE),
                "EMAIL" => $this->input->post("email",TRUE),
                "COMPANYNAME" => $this->input->post("companyname",TRUE),
                "CLIENTADDRESS" => $this->input->post("clientaddress",TRUE),
                "CITY" => $this->input->post("city",TRUE),
                "STATE_PROVINCE_COUNTY" => $this->input->post("state_province_county",TRUE),
                "ZIP" => $this->input->post("zip",TRUE),
                "COUNTRY" => $this->input->post("country",TRUE),
                "PHONENUMBER" => $this->input->post("phonenumber",TRUE),
                "MOBILE" => $this->input->post("mobile",TRUE),
                "EMAIL" => $this->input->post("email",TRUE),
                "BROCHURE" => ($this->input->post("brochure",TRUE) == 1) ? 'YES' : 'NO',
                "MAILINGLIST" => ($this->input->post("mailinglist",TRUE) == 1) ? 'YES' : 'NO',
                "PROFESSIONALDESIGNATIONS" => $this->input->post("professionaldesignation",TRUE),
                "COMMENTS" => $this->input->post("comments",TRUE),
                "TIMESTAMP" => date('l jS \of F Y \a\t h:i:s A')
                );

        send_email(EMAIL_SENDER, 
                    EMAIL_SENDER_NAME, 
                    EMAIL_RECEIVER, 
                    $this->lang->line('Registration_comments_subject'), 
                    $template_file,
                    $template_data);

    }       

}

/* End of file users.php */
/* Location: ./system/application/modules/frontoffice/controllers/home.php  */ 